package com.lord.otter.component.tools.business.chain;


import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

public class BusinessContext<T extends BusinessContextAttributeDefinitionTable> {

    private Map<String, Object> context = new HashMap<>();

    @JsonIgnore

    public Map<String, Object> getContext() {
        return context;
    }

    public void setAttribute(T t, Object o) {
        if (!t.getAttributeClass().isInstance(o)) {
            throw new RuntimeException("类型不匹配");
        }
        context.put(t.getAttributeName(), o);
    }

    public <V> V getAttribute(T t) {
        Object o = context.get(t.getAttributeName());
        return (V) o;
    }

    public <V> V computeIfAbsent(T t, Function<T, ? extends V> mappingFunction) {
        Object attribute = getAttribute(t);
        if (Objects.nonNull(attribute)) {
            return (V) attribute;
        }
        V v = mappingFunction.apply(t);
        setAttribute(t, v);
        return v;
    }
}
